<template>
    <div class="loginContainer">
        <el-form
            class="loginForm"
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            auto-complete="on"
        >
            <!--<el-row class="logo">
                 <el-col :span="18">
                    <img :src="require('@/assets/img/logo.png')" alt="">
                    <p class="sysTit">全渠道智能客户服务平台</p>
                    <p>Intelligent Customer</p>
                </el-col>
                <el-col :span="6" style="margin-top: 20px;text-align: right;">
                    <i class="el-icon-phone" style="vertical-align: middle;"></i>
                    <span style="font-size: 14px;color: #495060;margin-left: 5px;vertical-align: middle;">61068594</span>
                </el-col>
            </el-row>-->
            <div class="logoTit">
                <p>
                    <img
                        :src="require('@/assets/img/khindex/signInlogo2.png')"
                        alt
                        width="220px"
                        height="65px"
                    />
                </p>
                <!-- <h3 style="font-size: 20px; margin: 15px 0 15px 0">全渠道智能客户服务平台</h3> -->
            </div>
            <div class="loginContent">
                <!-- <el-form-item label-position="left" prop="bankNum">
                    <el-input placeholder="银行号" v-model="loginForm.bankNum" type="text" name="bankNum"></el-input>
                </el-form-item>-->
                <el-form-item label-position="left" prop="userName">
                    <img src="@/icons/svg/user.svg" class="svgImg" alt />
                    <el-input
                        placeholder="用户名"
                        v-model="loginForm.userName"
                        class="elinput"
                        type="text"
                        name="userName"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <img src="@/icons/svg/password.svg" class="svgImg" alt />
                    <el-input
                        placeholder="密码"
                        class="elinput"
                        v-model="loginForm.password"
                        name="password"
                        @keyup.enter.native="toLogin"
                        type="password"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="coilIn">
                    <el-select
                        class="elinput"
                        v-model="loginForm.coilIn"
                        placeholder="是否在线"
                        name="coilIn"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-service"></i>
                        <el-option label="在线" value="在线"></el-option>
                        <el-option label="离线" value="离线"></el-option>
                    </el-select>
                    <!-- <el-input
                        placeholder="是否在线"
                        class="elinput"
                        v-model="loginForm.password"
                        name="password"
                        prefix-icon="el-icon-search"
                    ></el-input>-->
                </el-form-item>
                <!--<el-form-item prop="verifyCode" style="position: relative;">-->
                <!--<el-input placeholder="验证码" v-model="loginForm.verifyCode"></el-input>-->
                <!--<img :src="verifyCode" @click="getVerCode" class="showImage">-->
                <!--</el-form-item>-->
                <!-- <span class="forgetPsd" @click="forgetPass">忘记密码</span> -->
                <div>
                    <el-button
                        class="loginBtn"
                        @click.native.prevent="toLogin"
                        :loading="loading"
                    >登录</el-button>
                </div>
            </div>
        </el-form>
        <el-dialog
            v-drag
            :visible.sync="forgetPassDialog"
            :close-on-click-modal="false"
            append-to-body
            center
            width="500px"
        >
            <div slot="title">忘记密码</div>
            <el-form
                :model="Edit"
                class="menu-setting text_center"
                label-position="right"
                ref="Edit"
                label-width="110px"
                :rules="formRules"
                size="small"
            >
                <!-- <el-form-item label="银行号" prop="bankNum">
                    <el-input v-model="Edit.bankNum" placeholder="请输入"/>
                </el-form-item>-->
                <el-form-item label="用户账号" prop="userAccount">
                    <el-input v-model="Edit.userAccount" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="手机号码" prop="userPhone">
                    <el-input v-model="Edit.userPhone" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="验证码" prop="msgCode">
                    <el-input v-model="Edit.msgCode" placeholder="请输入" />
                    <el-button size="small" @click="getCode" class="code-btn">
                        <span v-show="show">获取验证码</span>
                        <span v-show="!show" class="count">{{ count }} s</span>
                    </el-button>
                </el-form-item>
                <el-form-item label="密码" prop="userPass">
                    <el-input type="password" v-model="Edit.userPass" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="确认密码" prop="repeatUserPass">
                    <el-input type="password" v-model="Edit.repeatUserPass" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    icon="el-icon-circle-close"
                    @click="forgetPassDialog = false"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="submitForgetPass"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                >确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue';
import { mapState } from 'vuex';
import { base64Encode } from '@/utils/Common';
import { getToken, removeToken, removeTokenToname } from '@/utils/auth';
import { RegConfig } from '@/utils/RegConfig';

export default {
    name: 'Login',
    data() {
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入新密码'));
            } else {
                if (this.Edit.repeatUserPass !== '') {
                    this.$refs.Edit.validateField('repeatUserPass');
                }
                callback();
            }
        };
        const validateRepeatPass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.Edit.userPass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            isShowIframe: false, // isShowIframe加载
            iframeUrl: '', // iframe 链接前缀地址
            BANKNUM: '6440', // 银行号
            USERID: '', // 登录用户工号
            loading: false,
            show: true,
            forgetPassDialog: false,
            loginRules: {
                bankNum: [{
                    required: true,
                    trigger: 'blur',
                    message: '请输入银行号',
                }],
                userName: [{
                    required: true,
                    trigger: 'blur',
                    message: '请输入用户名',
                }],
                password: [{
                    required: true,
                    trigger: 'blur',
                    message: '请输入密码',
                }],
                verifyCode: [{
                    required: true,
                    trigger: 'blur',
                    message: '请输入验证码',
                }],
            },
            Edit: {
                bankNum: '6440',
                userAccount: '',
                userPhone: '',
                userPass: '',
                repeatUserPass: '',
                msgCode: '',
            },
            formRules: {
                bankNum: [
                    { required: true, message: '请输入银行号', trigger: 'blur' },
                ],
                userAccount: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                ],
                userPhone: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { pattern: RegConfig.mobile, message: '请输入11位有效手机号码', trigger: 'blur' },
                ],
                userPass: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{6,16}$/, message: '密码为数字,大小写字母,特殊符号,至少包含三种,长度为6-16', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' },
                ],
                repeatUserPass: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { validator: validateRepeatPass, trigger: 'blur' },
                ],
                msgCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                ],
            },
            count: 60,
            verifyCode: '',
            loginForm: {
                bankNum: '6440',
                userName: '',
                password: '',
                verifyCode: '',
                coilIn: '在线',//在线状态 在线 离线
            },
            localIp: '',
            timer: null,

        };
    },
    components: {
        SvgIcon,
    },
    created() {
        // this.getVerCode();
        //   this.setBankNo();
        const agent = navigator.userAgent.toLowerCase();
        console.log(agent);
        // IE浏览器，需要将服务器加入受信任的站点，并启用安全级别里的“对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本”
        // if (agent.indexOf('trident') > 0) {
        //     this.ieIp();
        // } else { // 除IE外的其他浏览器
        //     this.getClientIP();
        // }
    },

    mounted() {
        // 监听页面显示
        document.addEventListener('visibilitychange', this.handleShowPage);
        // this.getClientIP((ip) => {
        //     console.log('ip=====' + ip);
        //     this.localIp = ip;
        // });
    },

    destroyed() {
        document.removeEventListener('visibilitychange', this.handleShowPage);
    },

    computed: mapState({
        defaultParams: state => state.common.defaultParams, // 卡系统交易请求报文
        inlineParams: state => state.common.inlineParams, // 卡系统交易请求报文
    }),

    methods: {

        handleShowPage(e) {
            if (e.target.visibilityState === 'visible') {
                if (getToken()) { // 用户已经登录 ->直接跳转首页
                    this.$router.push('/index/home');
                }
            }
        },
        // 忘记密码
        forgetPass() {
            this.forgetPassDialog = true;
            this.$nextTick(() => {
                if (this.$refs.Edit.resetFields()) {
                    this.$refs.Edit.resetFields();
                }
            });
        },

        submitForgetPass() {
            const params = {
                bankNum: this.Edit.bankNum,
                userAccount: this.Edit.userAccount,
                userPhone: this.Edit.userPhone,
                userPass: base64Encode(this.Edit.userPass),
                msgCode: this.Edit.msgCode,
            };
            this.$refs.Edit.validate((valid) => {
                if (valid) {
                    this.$post.user.forgetPwd(params).then((res) => {
                        if (res.data.success) {
                            this.$message.success('修改成功!');
                            this.forgetPassDialog = false;
                            this.$post.user.logout().then((res) => {
                                if (res.data.success) {
                                    sessionStorage.clear();
                                    localStorage.clear();
                                    Cookies.clear();
                                    // removeToken();
                                    // removeTokenToname(),
                                    this.$router.push({
                                        // 跳转到登陆页面
                                        name: 'Login',
                                    });
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            });
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
                }
            });
        },

        // 获取验证码
        getVerCode() {
            this.$post.user.getVerifyCode()
                .then((res) => {
                    if (res.data.success) {
                        this.verifyCode = `data:image/jpeg;base64,${res.data.content}`;
                    } else {
                        this.$message.error(res.data.content ? res.data.content : res.data.msg);
                    }
                });
        },
        // 获取验证码
        getCode() {
            if (!this.Edit.bankNum) {
                this.$message.warning('请先输入银行号');
                return;
            }
            const params = {
                userAccount: this.Edit.userAccount,
                userPhone: this.Edit.userPhone,
                busiName: '忘记密码',
                tranCode: '6440',
                bankNum: this.Edit.bankNum, // 银行号
                bnknbr: this.Edit.bankNum, // 银行号
            };
            if (this.Edit.userPhone === '') {
                this.$message.warning('请输入手机号！');
                return;
            }
            this.$post.user.sendMsgCode(params).then((res) => {
                if (res.data.success) {
                    if (!this.timer) {
                        this.count = 60;
                        this.show = false;
                        this.timer = setInterval(() => {
                            if (this.count > 0 && this.count <= 60) {
                                this.count--;
                            } else {
                                this.show = true;
                                clearInterval(this.timer);
                                this.timer = null;
                            }
                        }, 1000);
                    }
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },

        // 跑登录接口
        toLogin() {
            if (this.loading) {
                return;
            }
            console.log(this.localIp, 'this.localIp')
            this.$refs.loginForm.validate((valid) => {
                sessionStorage.setItem('coilIn', this.loginForm.coilIn);
                if (valid) {
                    this.loading = true;
                    const data = {
                        ip: this.localIp,
                        // ip: '38.62.164.33',
                        userName: this.loginForm.userName,
                        password: base64Encode(this.loginForm.password), // this.loginForm.password, //base64Encode(this.loginForm.password),
                        verifyCode: this.loginForm.verifyCode,
                        userAccount: '',
                        bankNum: this.loginForm.bankNum, // 银行号
                    };
                    this.$post.user.login(data).then((res) => {
                        this.loading = false;
                        if (res.data.success) {
                            const { bankNum } = data;
                            // setToken(bankNum);
                            // localStorage.setItem('bankNo', bankNum);
                            window.timeOutFlag = false;
                            const { userInfo, teamInfo } = res.data.content;
                            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
                            const inlineParams = JSON.parse(JSON.stringify(this.inlineParams));
                            defaultParams.sysHead.agentName = userInfo.userName;
                            inlineParams.sysHead.agentName = userInfo.userName;

                            defaultParams.sysHead.loginID = userInfo.userAccount;
                            inlineParams.sysHead.loginID = userInfo.userAccount;

                            defaultParams.sysHead.ctiNo = userInfo.ctiNum;
                            inlineParams.sysHead.ctiNo = userInfo.ctiNum;

                            defaultParams.body.appHead.opeNo = userInfo.agNum;
                            inlineParams.body.appHead.opeNo = userInfo.agNum;

                            defaultParams.body.appHead.bnknbr = bankNum || '6440';
                            inlineParams.body.appHead.bnknbr = bankNum || '6440';

                            this.$store.commit('common/UPDATE_DEFAULT_PARAMS', defaultParams);
                            this.$store.commit('common/UPDATE_INLINE_PARAMS', inlineParams);
                            this.$store.commit('user/UPDATE_USER_INFO', userInfo);
                            this.$store.commit('user/UPDATE_TEAMTNFO', teamInfo);

                            this.$router.push({
                                // 指定页面跳转到的页面
                                path: '/index/home',
                            });
                        } else {
                            this.$message.error(res.data.content ? res.data.content : res.data.msg);
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        // 获取本地ip地址
        getLocalIp() {
            console.log('获取ip方法');
            const that = this;
            const myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
            const pc = new myPeerConnection({ iceServers: [] });
            const noop = function () { };
            const localIps = {};
            const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
            let key;
            const ipIterate = (ip) => {
                if (!localIps[ip]) {
                    that.localIp = ip;
                }
                localIps[ip] = true;
            };
            pc.createDataChannel('');
            pc.createOffer().then((res) => {
                res.sdp.split('\n').forEach((item) => {
                    if (item.indexOf('candidate') < 0) return;
                    item.match(ipRegex).forEach(ipIterate);
                });
                pc.setLocalDescription(res, noop, noop);
            });
            pc.onicecandidate = (ice) => {
                if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
                ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
            };
        },

        // 获取ip
        /**
         * 除IE浏览器外的其他浏览器获取客户端IP
         */
        getClientIP() {
            const isValidIP = (ip) => {
                const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                return reg.test(ip);
            };
            const that = this;
            const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
            if (RTCPeerConnection) {
                const rtc = new RTCPeerConnection({
                    iceServers: [],
                });
                if (1 || window.mozRTCPeerConnection) {
                    rtc.createDataChannel('', {
                        reliable: false,
                    });
                }
                rtc.onicecandidate = function (evt) {
                    if (evt.candidate) grepSDP(`a=${evt.candidate.candidate}`);
                };
                rtc.createOffer((offerDesc) => {
                    grepSDP(offerDesc.sdp);
                    rtc.setLocalDescription(offerDesc);
                },
                    (e) => {
                        console.warn('offer failed', e);
                    });
                const addrs = Object.create(null);
                addrs['0.0.0.0'] = false;
                function updateDisplay(newAddr) {
                    if (newAddr in addrs) return;
                    addrs[newAddr] = true;
                    const displayAddrs = Object.keys(addrs).filter(k => addrs[k]);
                    for (let i = 0; i < displayAddrs.length; i++) {
                        if (displayAddrs[i].length > 16) {
                            displayAddrs.splice(i, 1);
                            i--;
                        }
                    }
                    if (isValidIP(displayAddrs[0])) {
                        that.localIp = displayAddrs[0];
                    }
                }
                function grepSDP(sdp) {
                    const hosts = [];
                    sdp.split('\r\n').forEach((line, index, arr) => {
                        if (~line.indexOf('a=candidate')) {
                            var parts = line.split(' ');
                            var addr = parts[4];
                            const type = parts[7];
                            if (type === 'host') updateDisplay(addr);
                        } else if (~line.indexOf('c=')) {
                            var parts = line.split(' ');
                            var addr = parts[2];
                            updateDisplay(addr);
                        }
                    });
                }
            }
            // var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
            // if (RTCPeerConnection) (() => {
            //     var rtc = new RTCPeerConnection()
            //     rtc.createDataChannel(''); //创建一个可以发送任意数据的数据通道
            //     rtc.createOffer(offerDesc => { //创建并存储一个sdp数据
            //         rtc.setLocalDescription(offerDesc)
            //     }, e => { console.log(e) })
            //     rtc.onicecandidate = (evt) => { //监听candidate事件
            //         if (evt.candidate) {
            //             console.log(evt.candidate);
            //             var ip_addr = evt.candidate.address
            //             localStorage.setItem('ip_addr', ip_addr)
            //             console.log("ip_addr===" + localStorage.getItem('ip_addr'))
            //             this.localIp = localStorage.getItem('ip_addr');
            //         }
            //     }
            // })()
            // else { console.log("chrome浏览器OK") }
        },

        /**
         * IE浏览器获取客户端IP
         */
        ieIp() {
            let IeIPStr = '';
            const IeLocator = new ActiveXObject('WbemScripting.SWbemLocator');
            const IeService = IeLocator.ConnectServer('.');
            const IeProperties = IeService.ExecQuery('SELECT IPAddress FROM Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE');
            const IeEnum = new Enumerator(IeProperties);
            const isValidIP = (ip) => {
                const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                return reg.test(ip);
            };
            for (; !IeEnum.atEnd(); IeEnum.moveNext()) {
                const Iep = IeEnum.item();
                if (isValidIP(Iep.IPAddress(0))) {
                    IeIPStr = Iep.IPAddress(0);
                }
            }
            this.localIp = IeIPStr;
            // return IeIPStr;
        },

    },

};
</script>

<style scoped  lang="scss">
.svg-container {
    padding: 6px 5px 6px 15px;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
}

/deep/ .el-form-item__content {
    line-height: 0 !important;
}
.code-btn {
    height: 30px;
    top: 1px;
    position: absolute;
    right: 103px;
    background: #fff;
    cursor: pointer;
    color: #ef8466;
    border: none;
}
.loginContainer {
    position: fixed;
    height: 100%;
    width: 100%;
    background-image: url("../../assets/img/khindex/login_image.png");
    background-size: 100% 100%;
    .svgImg {
        width: 18px;
        position: absolute;
        z-index: 10;
        left: 16%;
        top: 11px;
    }
    .loginLeft {
        position: absolute;
        width: 50%;
        text-align: left;
        h1 {
            font-weight: normal;
            color: #fff;
            line-height: 1.2;
            padding-top: 25%;
            margin-left: 12%;
        }
        p {
            max-width: 600px;
            font-size: 16px;
            line-height: 30px;
            color: #fff;
            margin: 24px 100px 0 12%;
            opacity: 0.8;
        }
    }
    .loginForm {
        position: absolute;
        right: 13%;
        width: 20%;
        min-width: 255px;
        background: #fff;
        height: 58%;
        min-height: 400px;
        border-radius: 8px;
        top: 0;
        bottom: 0;
        margin: auto;
        .logo {
            height: 22%;
            padding: 20px;
            img {
                float: left;
                margin-left: 20px;
                width: 45px;
                height: 45px;
            }
            p {
                text-align: left;
                margin-left: 80px;
                font-size: 12px;
                font-weight: 600;
                font-family: cursive;
            }
            .sysTit {
                margin-top: 12px;
                font-size: 15px;
            }
        }
        .logoTit {
            height: 17%;
            margin-bottom: 10px;
            margin-top: 15%;
        }
        .loginContent {
            /deep/ .el-form-item__error {
                left: 15%;
            }
            /* height: 60%; */
            .forgetPsd {
                color: #3e89f5;
                font-size: 14px;
                display: inline-block;
                margin-left: 60%;
                margin-bottom: 20px;
                cursor: pointer;
            }
            .loginBtn {
                width: 70%;
                height: 8.5%;
                font-size: 20px;
                font-weight: 600;
                margin-top: 2%;
                color: #fff;
                background: linear-gradient(
                    180deg,
                    rgba(77, 165, 247, 1) 0%,
                    rgba(48, 110, 244, 1) 100%
                );
            }
            .showImage {
                position: absolute;
                width: 4rem;
                height: 38px;
                right: 15%;
            }
        }
    }
}
</style>
<style lang="scss">
.loginContainer {
    .loginContent {
        margin-top: 14px;
        .el-icon-service {
            color: #000;
        }
        .el-form-item__content > .el-input {
            margin-left: 2%;
            text-align: center;
            width: 76%;
            .el-input__icon {
                line-height: 40px;
                font-size: 20px;
            }
        }
        .el-form-item__content > .el-select {
            margin-left: 2%;
            text-align: center;
            width: 76%;
            .el-input input {
                background-color: #e8f0fe;
            }
        }
        .el-form-item {
            margin-bottom: 12px;
        }
        .el-input__inner {
            padding-left: 35px;
            height: 40px;
            line-height: 40px;
        }

        .el-form-item__content {
            text-align: center;
            .elinput .el-input__inner {
                width: 100%;
            }
        }
        .el-input--prefix .el-input__prefix .el-input__icon {
            font-size: 20px;
        }
    }
}
</style>
